package com.esreport.api;

import com.alibaba.fastjson.JSONObject;
import com.esreport.Utils.DateUtil;
import com.esreport.Utils.ResultJson;
import com.esreport.dto.ArticleInformation;
import com.esreport.service.ReportService;
import com.esreport.service.XOtherSourceService;
import com.esreport.service.XReportService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author cexy
 * @date 2020/1/8 17:19
 * @description: statistic项目使用
 */
@Slf4j
@RestController
@RequestMapping("/xreport")
public class XReportApi {

    @Autowired
    private XReportService XReportService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private XOtherSourceService xOtherSourceService;

    @RequestMapping(value = "/countHits", produces = "application/json; charset=utf-8")
    public Object countForHits(Integer siteId) {
        try {
            long hits = reportService.countHits(siteId);
            //今天点击量
            long todayHits = reportService.countHits(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            //昨天点击量
            long yesterdayHits = reportService.countHits(DateUtil.getBeginDayOfTDBYesterday(), DateUtil.getEndDayOfTDBYesterDay(), siteId);
            //本周点击量
            long weekHits = reportService.countHits(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            //上周点击量
            long lastweekHits = reportService.countHits(DateUtil.getBeginDayOfLastWeek(), DateUtil.getEndDayOfLastWeek(), siteId);
            //本月点击量
            long monthHits = reportService.countHits(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            //上月点击量
            long lastMonthHits = reportService.countHits(DateUtil.getBeginDayOfLastMonth(), DateUtil.getEndDayOfLastMonth(), siteId);
            //算昨天比前天的增量百分比
            float dayIncrease = yesterdayHits == 0 ? 0 : (Float.parseFloat(String.valueOf(todayHits)) - yesterdayHits) / yesterdayHits * 100;
            //周百分比
            float weekIncrease = lastweekHits == 0 ? 0 : ((Float.parseFloat(String.valueOf(weekHits)) - lastweekHits) / lastweekHits) * 100;
            //月百分比
            float monthIncrease = lastMonthHits == 0 ? 0 : ((Float.parseFloat(String.valueOf(monthHits)) - lastMonthHits) / lastMonthHits) * 100;
            DecimalFormat df = new DecimalFormat("0.00");
            JSONObject json = new JSONObject();
            json.put("todayHits", todayHits);
            json.put("weekHits", weekHits);
            json.put("monthHits", monthHits);
            json.put("allHits", hits);
            json.put("dayIncrease", df.format(dayIncrease) + "%");
            json.put("weekIncrease", df.format(weekIncrease) + "%");
            json.put("monthIncrease", df.format(monthIncrease) + "%");
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 新增用户
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countForNewUser", produces = "application/json; charset=utf-8")
    public Object countForNewUser(Integer siteId) {
        try {
            long dayCount = reportService.countNewUser(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekCount = reportService.countNewUser(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthCount = reportService.countNewUser(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("todayNewUser", dayCount);
            json.put("weekNewUser", weekCount);
            json.put("monthNewUser", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 浏览新闻量
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/browseNews", produces = "application/json; charset=utf-8")
    public Object browseOfToday(Integer siteId) {
        try {
            long count = XReportService.countBrowseNews(siteId);
            long dayCount = reportService.countBrowse(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekCount = reportService.countBrowse(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthCount = reportService.countBrowse(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("allBrowseNews", count);
            json.put("todayBrowseNews", dayCount);
            json.put("weekBrowseNews", weekCount);
            json.put("monthBrowseNews", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 用户总停留时间
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/sumStayTime", produces = "application/json; charset=utf-8")
    public Object sumStayTime(Integer siteId) {
        try {
            long sum = XReportService.sumStayTime(siteId);
            long daySum = reportService.sumStayTime(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekSum = reportService.sumStayTime(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthSum = reportService.sumStayTime(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("sumStayTime", sum);
            json.put("todaySumStayTime", daySum);
            json.put("weekSumStayTime", weekSum);
            json.put("monthSumStayTime", monthSum);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 用户总停留平均时间
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/avgStayTime", produces = "application/json; charset=utf-8")
    public Object avgStayTime(Integer siteId) {
        try {
            long sum = XReportService.countAvgStayTime(siteId);
            long daySum = XReportService.countAvgStayTime(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekSum = XReportService.countAvgStayTime(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthSum = XReportService.countAvgStayTime(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("avgStayTime", sum);
            json.put("todayAvgStayTime", daySum);
            json.put("weekAvgStayTime", weekSum);
            json.put("monthAvgStayTime", monthSum);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 查询站点累计用户
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/userCount", produces = "application/json; charset=utf-8")
    public Object userCount(String siteId) {
        Integer count = xOtherSourceService.countUser(siteId);
        if (count < 0) {
            return ResultJson.errorMes("服务器异常");
        }
        JSONObject json = new JSONObject();
        json.put("userCount", count);
        return ResultJson.successResult("请求成功", json);
    }

    /**
     * 按新闻点击量排序  数量动态传参
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/articleTopList", produces = "application/json; charset=utf-8")
    public Object topList(Integer siteId) {
        Date start = DateUtil.getDayBegin();
        Date end = DateUtil.getDayEnd();
        /*Date weekStart = DateUtil.getBeginDayOfWeek();
        Date weekEnd = DateUtil.getEndDayOfWeek();
        Date monthStart = DateUtil.getBeginDayOfMonth();
        Date monthEnd = DateUtil.getEndDayOfMonth();*/
        Date weekStart = DateUtil.getFrontDay(start, 7);
        Date monthStart = DateUtil.getFrontDay(start, 30);
        Date allStart = DateUtil.getFrontYear(start, 10);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            List<ArticleInformation> dayArticleInformations = xOtherSourceService.getTopArticle(siteId, 10, sf.format(start), sf.format(end));
            List<ArticleInformation> weekArticleInformations = xOtherSourceService.getTopArticle(siteId, 10, sf.format(weekStart), sf.format(end));
            List<ArticleInformation> monthArticleInformations = xOtherSourceService.getTopArticle(siteId, 10, sf.format(monthStart), sf.format(end));
            List<ArticleInformation> allArticleInformations = xOtherSourceService.getTopArticle(siteId, 10, sf.format(allStart), sf.format(end));
            JSONObject json = new JSONObject();
            json.put("dayArticleTop", dayArticleInformations);
            json.put("weekArticleTop", weekArticleInformations);
            json.put("monthArticleTop", monthArticleInformations);
            json.put("allArticleTop", allArticleInformations);
            return ResultJson.successResult("请求成功", json);
        } catch (ParseException e) {
            return ResultJson.errorMes("时间格式不正确");
        } catch (IOException e) {
            log.warn(e.getMessage());
            return ResultJson.errorMes("服务器异常");
        }
    }


    /**
     * 统计上个月的分享总数
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countShare", produces = "application/json; charset=utf-8")
    public Object countShare(Integer siteId) {
        try {
            long count = XReportService.countShare(siteId);
            long dayCount = reportService.countShare(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekCount = reportService.countShare(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthCount = reportService.countShare(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("allCountShare", count);
            json.put("todayCountShare", dayCount);
            json.put("weekCountShare", weekCount);
            json.put("monthCountShare", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 首次启动数
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countFirstStart", produces = "application/json; charset=utf-8")
    public Object countFirstStart(Integer siteId) {
        try {
            long count = XReportService.countFirstStart(siteId);
            long dayCount = XReportService.countFirstStart(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekCount = XReportService.countFirstStart(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthCount = XReportService.countFirstStart(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("allCountFirstStart", count);
            json.put("todayCountFirstStart", dayCount);
            json.put("weekCountFirstStart", weekCount);
            json.put("monthCountFirstStart", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 总启动数
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countStart", produces = "application/json; charset=utf-8")
    public Object countStart(Integer siteId) {
        try {
            long count = XReportService.countStart(siteId);
            long dayCount = XReportService.countStart(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
            long weekCount = XReportService.countStart(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            long monthCount = XReportService.countStart(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("allCountStart", count);
            json.put("todayCountStart", dayCount);
            json.put("weekCountStart", weekCount);
            json.put("monthCountStart", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }


    /**
     * 分享新闻排行（目前查询前10条）
     *
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countShareRank", produces = "application/json; charset=utf-8")
    public Object countShareRank(Integer siteId) {
        try {
            Date start = DateUtil.getDayBegin();
            Date end = DateUtil.getDayEnd();
            List<Map> count = XReportService.countShareRank(siteId);
            List<Map> dayCount = XReportService.countShareRank(start, end, siteId);
           /* List<Map> weekCount = XReportService.countShareRank(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
            List<Map> monthCount = XReportService.countShareRank(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);*/
            List<Map> weekCount = XReportService.countShareRank(DateUtil.getFrontDay(start, 7), end, siteId);
            List<Map> monthCount = XReportService.countShareRank(DateUtil.getFrontDay(start, 30), end, siteId);
            JSONObject json = new JSONObject();
            json.put("allShareRank", count);
            json.put("todayShareRank", dayCount);
            json.put("weekShareRank", weekCount);
            json.put("monthShareRank", monthCount);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    @RequestMapping(value = "/granularQuery", produces = "application/json; charset=utf-8")
    public Object weekGranularQuery(Integer siteId) {
        Date end = DateUtil.getDayEnd();
        Date dayEnd = DateUtil.addSec(DateUtil.getDayEnd(), 8 * 60 * 60);
        Date startDay = DateUtil.addSec(DateUtil.getFrontDay(end, 7), 8 * 60 * 60);
        Date weekEnd = DateUtil.addSec(DateUtil.getEndDayOfWeek(), 8 * 60 * 60);
        Date startWeek = DateUtil.addSec(DateUtil.getFrontDay(end, 7 * 9), 8 * 60 * 60);
        Date monthEnd = DateUtil.addSec(DateUtil.getEndDayOfMonth(), 8 * 60 * 60);
        Date startMonth = DateUtil.getFrontMonth(DateUtil.addSec(DateUtil.getFrontYear(end, 1), 8 * 60 * 60), -1);

        try {
            List<Map> day = XReportService.granularQuery(startDay, dayEnd, siteId, DateHistogramInterval.DAY);
            List<Map> week = XReportService.granularQuery(startWeek, weekEnd, siteId, DateHistogramInterval.WEEK);
            List<Map> month = XReportService.granularQuery(startMonth, monthEnd, siteId, DateHistogramInterval.MONTH);
            JSONObject json = new JSONObject();
            json.put("dayGranularQuery", day);
            json.put("weekGranularQuery", week);
            json.put("monthGranularQuery", month);
            return ResultJson.successResult("请求成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }
}
